package cn.tedu.mall.product.filter;

import cn.tedu.mall.common.pojo.sso.authentication.CsmallAuthenticationInfo;
import cn.tedu.mall.common.utils.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.List;

/**
 * 通过验证jwt验证登录
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Autowired
    private StringRedisTemplate  stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
//        httpServletResponse.setHeader("Access-Control-Allow-Origin",httpServletRequest.getHeader("Orgin"));
//        httpServletResponse.setHeader("Access-Control-Allow-Credentials","true");
//        httpServletResponse.setHeader("Access-Control-Allow-Methods","*");
//        httpServletResponse.setHeader("Access-Aontrol-Allow-Headers","authorization,content-type,Cookie");
//        httpServletResponse.setHeader("Access-Aontrol-Expose-Headers","Authorization,BiToken,Cookie");



        String token = getTokenFromHeader(httpServletRequest);

        if(ObjectUtils.isEmpty(httpServletRequest.getHeader("Origin"))){
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        }else{
            httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        }
//        response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
//        response.setHeader("Access-Control-Expose-Headers", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
        //response.setHeader("Access-Control-Allow-Credentials", "true");
        System.out.println(httpServletRequest.getMethod()+"method");
        if ("OPTIONS".equals(httpServletRequest.getMethod())) {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }




        if (ObjectUtils.isEmpty(token)){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }else{
            String blackListKey="mall:sso:black:list:token:";
            SetOperations<String, String> operations = stringRedisTemplate.opsForSet();
            if (operations.isMember(blackListKey,token)){
                filterChain.doFilter(httpServletRequest,httpServletResponse);
                return;
            }
            CsmallAuthenticationInfo userInfo=null;
            try {
                 userInfo = jwtTokenUtils.getUserInfo(token);
                SecurityContext context = SecurityContextHolder.createEmptyContext();
                List<GrantedAuthority> authorities=new ArrayList<>();
                for (String authority : userInfo.getAuthorities()) {
                    SimpleGrantedAuthority simpleGrantedAuthority=new SimpleGrantedAuthority(authority);
                    authorities.add(simpleGrantedAuthority);
                }
                UsernamePasswordAuthenticationToken authentication=
                        new UsernamePasswordAuthenticationToken(userInfo.getUsername(),null,authorities);
                context.setAuthentication(authentication);
                SecurityContextHolder.setContext(context);
                filterChain.doFilter(httpServletRequest,httpServletResponse);
            }catch (Exception e){
                filterChain.doFilter(httpServletRequest,httpServletResponse);
                return;
            }


        }
    }

    private String getTokenFromHeader(HttpServletRequest request) {
        String bearerToken = request.getHeader("Bearer");
        if (!ObjectUtils.isEmpty(bearerToken)) {
            return bearerToken;
        }
        String authorizationToken = request.getHeader("Authorization");
        if (!ObjectUtils.isEmpty(authorizationToken)) {
            String token=authorizationToken.substring(7);
            return token;
        }
        return null;

    }
}
